#coding:utf8
#
# Author: CMGS
# Created on 2010-12-6
#

import time
import datetime
import threading

from libs import memory as _memory
from common import config as _config

class Logger(object):
    
    def __init__(self):
        self._loggers = {}
        self._mapping = {}
        self._lock = threading.RLock()
        self._init()
        self._begin = datetime.date.today()

    def record(self, level, k, v):
        self._lock.acquire()
        now = datetime.date.today()
        v = ''.join(v)
        try:
            # 判断是否分文件
            if (now - self._begin).days > _config.SPLIT_TIME:
                self.closeFile()
                self._begin = now
            # 判断pool是否满了
            if self._loggers[level].getCount() >= self._loggers[level].getMaxSize():
                self._writeToFile(level)
            if not self._loggers[level].add(k, [v]):
                self._loggers[level].get(k).append(v)
        except Exception, e:
            # 考虑如何输出 e
            print e

        self._lock.release()
        
    def closeFile(self):
        self._lock.acquire()
        try:
            for logger in _config.LOGGERS:
                self._writeToFile(logger[0])
                f = self._mapping[logger[0]]
                f.close()
            # init loggers again
            self._init()
        except Exception, e:
            print e
        finally:
            self._lock.release()

    def _writeToFile(self, level):
        f = self._mapping[level]
        for k in self._loggers[level].getIndex():
            t = time.strftime('%Y-%m-%d %X', time.localtime(k))
            for l in self._loggers[level].get(k):
                s = '%s %s - %s \n' % (t, level, l)
                f.write(s)
            f.flush()
        self._loggers[level].empty()
        
    def _init(self):
        size = _config.LOGGER_DEFAULT_SIZE
        for logger in _config.LOGGERS:
            if len(logger) == 3:
                self._loggers[logger[0]] = _memory.MemoryPool(logger[2])
            else:
                self._loggers[logger[0]] = _memory.MemoryPool(size)
            fileName = '%s.%s' % (logger[1], time.strftime("%Y-%m-%d",time.localtime()))
            self._mapping[logger[0]] = open(fileName, 'a')

if __name__ == '__main__':
    log = Logger()
    for i in range(1, 20):
        log.record('error', time.time(), str(i))
    log.closeFile('error')
